//
//  AppDelegate.m
//  TestWebview
//
//  Created by 谭谭伟 on 17/3/8.
//  Copyright © 2017年 谭谭伟. All rights reserved.
//

#import "AppDelegate.h"
#import "MNDMainViewController.h"
#import "UserDefaultsTool.h"
#import <SVProgressHUD.h>
#import "MNDThirdPartySDK.h"
#import <Bugly/Bugly.h>

@interface AppDelegate ()
/* */
@property (strong, nonatomic) MNDMainViewController *mndViewController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //Bugly崩溃报告
    [self configBugly];
    
    //检测并清空数据
    [self clearOldData];
//    NSDictionary *user_code = [UserDefaultsTool objetForKey:@"user_code"];
//    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:user_code];
//    if (cookie == nil) {
//    
//        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
//    }
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
     MNDMainViewController *mndViewController =  [[MNDMainViewController alloc] init];
    mndViewController.view.backgroundColor = [UIColor whiteColor];
    self.mndViewController = mndViewController;
    UINavigationController *navgationController = [[UINavigationController alloc]initWithRootViewController:mndViewController];

    _window.rootViewController = navgationController;
    [_window makeKeyAndVisible];
    
    //加载网络数据
    [mndViewController loadWebviewData];
    //如果用户没有退出，进入时需要输入手势
    NSString *psswordDocuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *passwordFilePath = [psswordDocuPath stringByAppendingPathComponent:@"password"];
    NSString *password = [NSKeyedUnarchiver unarchiveObjectWithFile:passwordFilePath];
    
    if (password != nil) {
        [UserDefaultsTool saveBool:YES forKey:@"confirmPassword"];
        [mndViewController gotoGestureVC];
        
    }
    //启动页延迟
    [NSThread sleepForTimeInterval:3.5];

    if (mndViewController.featureVersion == NO) {
//            [SVProgressHUD showWithStatus:@"努力加载中..."];
    }
        
    return YES;
}

- (void)configBugly {
    BuglyConfig *buglyConfig = [[BuglyConfig alloc] init];
    buglyConfig.reportLogLevel = BuglyLogLevelWarn;
    buglyConfig.unexpectedTerminatingDetectionEnable = YES;
    
    [Bugly startWithAppId:(NSString *)Bugly_APPID config:buglyConfig];
}

- (void)clearOldData {
    NSString *versionKey = @"CFBundleShortVersionString";
    //取到上一次版本号
    NSString *previousVersion = [UserDefaultsTool objetForKey:versionKey];
    //取到当前版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[versionKey];
    if (![previousVersion isEqualToString:currentVersion]) {
        [UserDefaultsTool removeAllKey];
    }
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    //记录程序进入后台的时间,并保存
    NSDate *date = [NSDate date];
    [UserDefaultsTool saveObject:date forKey:@"enterBackgroundTime"];
   
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    //判断是否要显示手势密码解锁
    [self showGestureLock];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark -弹出手势锁判定

- (void)showGestureLock {
   
    //获取进入后台时间
    NSDate *enterBackgroundTime = [UserDefaultsTool objetForKey:@"enterBackgroundTime"];
    //计算间隔
    NSInteger interval = [enterBackgroundTime timeIntervalSinceNow];
    //如果已设置密码,已登陆,并且进入后台时间超过10秒，弹出手势解锁
    //取到保存的密码
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *passwordFilePath = [docuPath stringByAppendingPathComponent:@"password"];
    NSString *password= [NSKeyedUnarchiver unarchiveObjectWithFile:passwordFilePath];
//    NSString *password = [UserDefaultsTool objetForKey:@"password"];
    BOOL singIn = [UserDefaultsTool boolForKey:@"signIn"];
    BOOL gestureSwitch = [UserDefaultsTool boolForKey:@"gestureSwitch"];
    if(interval < -10 && (password && password.length != 0) && (singIn == YES) && (gestureSwitch == YES)) {
        
        [[NSNotificationCenter defaultCenter]  postNotificationName:@"showGesture" object:nil];
        [UserDefaultsTool saveBool:YES forKey:@"confirmPassword"];
    }
    
}


@end


